﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Nova_DAL;
using System.Data.Common;
using Nova_Common;
using System.Text;
public partial class System_Position_PositionInit : System.Web.UI.Page
{
   #region 变量定义
    DataSet ds = new DataSet();
    DbHelper dbHelper = new DbHelper();
    DbCommand cmd = null;
    string strSQL = "";
    int lane = 0, layer = 0, col = 0, line = 0;
   #endregion

   #region 画面操作
    protected void Page_Load(object sender, EventArgs e)
    {
      
        if (!IsPostBack)
        {
            gv_Bind();
        }
        //验证TextBox
        string strJs = "";
        strJs = "return Validate(";
        strJs += "'txt_Lane','巷道号不为空','r'";
        strJs += ",'txt_Line','排数不为空','r'";
        strJs += ",'txt_Col','列数不为空','r'";
        strJs += ",'txt_Layer','层数不为空','r'";
        strJs += ");";
        ibtnSubmit.Attributes.Add("onclick", strJs);
      
       
    }
    /// <summary>
    /// 添加库区
    /// 添加之前的检验：1、非空；2、输入的为数据型，大于0，长度一,3、是否库区存在
    /// </summary>
    protected void ibtnSubmit_Click(object sender, ImageClickEventArgs e)
    {
        int result = 0;
        try
        {

            if (Ispast(txt_Lane.Text, 2) && Ispast(txt_Line.Text, 1) && Ispast(txt_Col.Text, 3) && Ispast(txt_Layer.Text, 2))
            {

                lane = Convert.ToInt32(txt_Lane.Text);
                line = Convert.ToInt32(txt_Line.Text);
                col = Convert.ToInt32(txt_Col.Text);
                layer = Convert.ToInt32(txt_Layer.Text);

                if (LaneCreated(lane) == 1)
                {
                     ShowBox.MessageBox(this, "该巷道已经存在，不能重复创建");
                     return;
                }

                for (int i = 1; i <= line; i++)
                    for (int j = 2; j <= col; j++)   //货位的列从2开始，输送机的列定义为1占用
                        for (int k = 1; k <= layer; k++)
                        {
                            result = AddPosition(lane, i, j, k);
                        }


                if (result > 0)
                {
                    ShowBox.MessageBox(this, "该巷道货位创建成功");
                }

              
            }
            else
            {
                ShowBox.MessageBox(this, "输入的巷道号、层数、列数或行数不合符要求，重新输入数据");
            }


            txt_Lane.Text = "";
            txt_Line.Text = "";
            txt_Col.Text = "";
            txt_Layer.Text = "";

            gv_Bind();
        }
        catch(Exception ex)
        {
            
            Console.Write(ex.ToString());
        }

        
       
    }
    //置空
    protected void ibtnReset_Click(object sender, ImageClickEventArgs e)
    {
        txt_Lane.Text = "";
        txt_Line.Text = "";
        
        txt_Col.Text = "";
        txt_Layer.Text = "";
    }

    //查询
    protected void ibtnQuery_Click(object sender, ImageClickEventArgs e)
    {
      
        gv_Bind();
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ibtnDel_Click(object sender, ImageClickEventArgs e)
    {
        int iCount = 0;
        CheckBox cbx = null;
        StringBuilder listId = new StringBuilder();
      try
       {
        for (int i = 0; i < gvPosition.Rows.Count; i++)
        {
            cbx = (CheckBox)gvPosition.Rows[i].Cells[0].FindControl("chkSelect");
            if (cbx.Checked)
            {

                listId.Append("'" + gvPosition.DataKeys[i].Value.ToString() + "',");

               
            }
        }

        if (listId.Length > 0)
         {

             iCount = DeletePosition(listId.ToString().TrimEnd(','));
             if (iCount > 0)
             {
                 ShowBox.MessageBox(this, "该巷道删除成功");

                 gv_Bind();
             }
             else 
             {
                 ShowBox.MessageBox(this, "货位表与其他表有关联，必须先删除其他表的数据后，才能删除货位表数据，删除失败！");

             }
         }
       }
       catch (Exception ex)
       {
         Response.Write(ex.ToString());
       }

    }

   #endregion

   #region 执行函数
    /// <summary>
    /// 创建货位（根据巷道、排、列、层）
    /// </summary>
    /// <param name="vlane"></param>
    /// <param name="vline"></param>
    /// <param name="vcol"></param>
    /// <param name="vlayer"></param>
    /// <returns></returns>
    protected int AddPosition(int vlane, int vline, int vcol, int vlayer)
    {
        int i = 0;
        long vPosID = 0;
     
        try
        {
            //货位的定义：Zone_ID默认为10代表立体库,其他仓库类型暂不考虑（数据库表中语句添加）
            string PosID = "10" + vlane.ToString().PadLeft(2, '0') + vline.ToString() + vcol.ToString().PadLeft(3, '0') + vlayer.ToString().PadLeft(2, '0') + "00";
           vPosID = Convert.ToInt64(PosID);

           int vRun_time = vlayer + vcol;

            strSQL = @"INSERT INTO [dbo].[TBase_Position]
                                       ([Pos_ID]
                                       ,[Zone_ID]
                                       ,[No_Lane]
                                       ,[No_Line]
                                       ,[No_Col]
                                       ,[No_Layer]
                                       ,[Run_time]
                                       )
                                 VALUES
                                       (@vPosID
                                       ,@vZone
                                       ,@vLane
                                       ,@vLine
                                       ,@vCol
                                       ,@vLayer
                                       ,@vRun_time
                                       )";
            DbCommand cmd = dbHelper.GetSqlStringCommond(strSQL);
            dbHelper.AddInParameter(cmd, "@vPosID", DbType.Int64, vPosID);
            dbHelper.AddInParameter(cmd, "@vZone", DbType.Int32, 10);

            dbHelper.AddInParameter(cmd, "@vLane", DbType.String, vlane);
            dbHelper.AddInParameter(cmd, "@vLine", DbType.Int32, vline);
            dbHelper.AddInParameter(cmd, "@vCol", DbType.Int32, vcol);
            dbHelper.AddInParameter(cmd, "@vLayer", DbType.Int32, vlayer);
            dbHelper.AddInParameter(cmd, "@vRun_time", DbType.Int32, vRun_time);


           i=dbHelper.ExecuteNonQuery(cmd);
        }
        catch (Exception ex)
        {
            Console.Write(ex.ToString());
        }
        return i;
    }
    
    /// <summary>
    /// 输入的文本框message是否是大于0的数据，以及长度是否满足（小于等于最大长度）
    /// </summary>
    /// <param name="message"></param>
    /// <param name="strlen"></param>
    /// <returns></returns>
    protected bool Ispast(string message,int strlen)
    {
        int result=0;
        int length =0;
        try
        {
          
            length = message.Length;
            if (length <= strlen)
            {
                result = Convert.ToInt32(message);
                if (result > 0)
                {     
                    return true;
                }
                else
                { return false; }
            }
            else
            { return false; }
        }
        catch
        {
            return false;
        }
    }


    //判断巷道是否已经存在  0:不存在；1：存在
    protected int LaneCreated(int No_Lane)
    {
        int res = 0;
        try
        {
            strSQL = @"SELECT No_Lane
                              FROM 
                                    TBase_Position
                              WHERE 
                                    No_Lane = @vNo_Lane";
            DbCommand cmd = dbHelper.GetSqlStringCommond(strSQL);
            dbHelper.AddInParameter(cmd, "@vNo_Lane", DbType.Int32, No_Lane);
            ds = dbHelper.ExecuteDataSet(cmd);
            if (ds.Tables[0].Rows.Count > 0)
            {
                res = 1;
            }
            

        }
        catch (Exception ex)
        {
            Console.Write(ex.ToString());
        }
        return res;
    }

    /// <summary>
    /// 巷道货位列表
    /// </summary>
    protected void gv_Bind()
    {
        try
        {
            // strSQL = "select No_Lane as 巷道号 ,MAX(No_Line) as 排数,MAX(No_Col) as 列数 ,MAX(No_Layer) as 层数 from TBase_Position where Zone_ID <> 20";

            //strSQL += " group by No_Lane  having 1=1 ";  //注意group前空格
            strSQL = "SELECT No_Lane AS 巷道号 ,MaxRows AS 排数,MaxCols AS 列数,MaxLayers AS 层数 FROM dbo.TLaneDefine WHERE 1=1 ";
            if (txt_Lane.Text != "")
            {
                strSQL += " and No_Lane = " + Convert.ToInt16(txt_Lane.Text.Trim()) + "";//注意前空格
            }
            if (txt_Line.Text != "")
            {
                strSQL += " and No_Line = " + Convert.ToInt16(txt_Line.Text.Trim()) + "";//注意前空格
            }
            if (txt_Col.Text != "")
            {
                strSQL += " and No_Col = " + Convert.ToInt16(txt_Col.Text.Trim()) + "";//注意前空格
            }
            if (txt_Layer.Text != "")
            {
                strSQL += " and No_Layer = " + Convert.ToInt16(txt_Layer.Text.Trim()) + "";//注意前空格
            }

            strSQL += " order by No_Lane ";
            cmd = dbHelper.GetSqlStringCommond(strSQL);
            ds = dbHelper.ExecuteDataSet(cmd);
            gvPosition.DataSource = ds;
            gvPosition.DataBind();
        }
        catch (Exception ex)
        {
            Console.Write(ex.ToString());
        }
    }
    /// <summary>
    /// 删除货位列表
    /// </summary>
    /// <param name="listId"></param>
    /// <returns></returns>
    public int DeletePosition(string listId)
    {
        int i = 0;
        try
        {

            strSQL = "delete from TBase_Position where  No_Lane in  (" + listId + ") ";
            DbCommand cmd = dbHelper.GetSqlStringCommond(strSQL);
            i = dbHelper.ExecuteNonQuery(cmd);
        }
        catch (Exception ex)
        {
            Console.Write(ex.ToString());
        }
        return i;
    }

  # endregion
    


    
}
